package study.alibaba.sentinel.support.rule;

import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import study.eggs.utils.JsonUtils;

import java.util.List;

/**
 * 降级规则
 */
@Slf4j
public class DegradeRuleInitFunc implements InitFunc {

    @Override
    public void init() throws Exception {
        List<DegradeRule> ruleLt = Lists.newArrayList();
        DegradeRule rule = new DegradeRule();

        //资源名
        rule.setResource("sayHi");

        //熔断策略（RT、异常比例、异常数量）
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        //降级的时间单位, 单位为s
        rule.setTimeWindow(10);

        //熔断时长
        rule.setCount(1);
        rule.setSlowRatioThreshold(1);
        //最小请求数
        rule.setMinRequestAmount(1);
        //统计时长
        rule.setStatIntervalMs(1);

        ruleLt.add(rule);

        log.info("load _2_degrade rule");
        DegradeRuleManager.loadRules(ruleLt);
    }

    public static void main(String[] args) {
        DegradeRule rule = new DegradeRule();

        //被保护的资源
        rule.setResource("sayHi");
        rule.setCount(1);
        //降级模式, RT（平均响应时间）、异常比例(DEGRADE_GRADE_EXCEPTION_RATIO)/异常数量
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        //降级的时间单位, 单位为s
        rule.setTimeWindow(10);
        System.out.println(JsonUtils.toJson(rule));
    }

}
